<script setup lang="ts">
  import { Search, Delete, Warning, CircleCheck, ArrowDown } from '@element-plus/icons-vue'
  import { ref, h } from 'vue'
  import { ElDivider, ElMessageBox } from 'element-plus'
  import {
    Action,
    MessageBoxState,
    TableInstance,
    ElTable,
    ElTableColumn,
    ElInput,
    ElDropdown,
    ElDropdownMenu,
    ElDropdownItem,
    ElIcon,
    ElSpace,
  } from 'element-plus'
  import Pagination from '@/components/Pagination/index.vue'
  import {
    useGetManualList,
    useManualDelByIds,
    useManualEnableByIds,
    useManualDisableByIds,
  } from '@/services/pages/know/useManual'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import ManualPreviewModal from './Preview.vue'
  import ManualFormModal from './FormModal.vue'

  const { listTotal, manualList, getListParam, getListLoading, getList } = useGetManualList()
  const { del } = useManualDelByIds()
  const { enable } = useManualEnableByIds()
  const { disable } = useManualDisableByIds()

  defineOptions({
    name: 'ManualList',
  })

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  // 分页组件实例
  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)

  // 表格组件实例
  const tableInstance = ref<TableInstance | null>(null)

  // 说明书id选择列表
  const manualSelectIds = ref<Array<string>>([])

  // 创建说明书弹窗显示状态
  const manualCreateModalVisible = ref(false)

  // 说明书预览弹窗显示状态
  const manualPreviewModalVisible = ref(false)

  // 正在预览的说明书的id
  const manualPreviewingId = ref('')

  // 正在更新的说明书的id
  const manualUpdatingId = ref('')

  /**
   * 说明书编辑事件
   * @param {String} id - 说明书id
   */
  const handleManualUpdate = (id: string) => {
    manualUpdatingId.value = id
    manualCreateModalVisible.value = true
  }

  /**
   * 说明书预览点击事件
   * @param {String} id - 说明书id
   */
  const handleManualPreview = (id: string) => {
    manualPreviewingId.value = id
    manualPreviewModalVisible.value = true
  }

  /**
   * 表格选择事件
   * @param {Array<ManualListItem>} manualList - 选择列表
   */
  const handleManualSelect = (manualList: Array<ManualListItem>) => {
    manualSelectIds.value = manualList.map((manual) => manual.id)
  }

  /**
   * 获取说明书列表
   */
  const _getList = () => {
    if (paginationInstance.value) {
      getListParam.value.limit = paginationInstance.value.size
      getListParam.value.page = paginationInstance.value.current
      getList()
    }
  }

  /**
   * 表格删除按钮点击事件
   * @param {ManualListItem} manual - 说明书对象
   */
  const handleTableDelClick = (manual: ManualListItem) => {
    if (tableInstance.value) {
      tableInstance.value.clearSelection()
      tableInstance.value.toggleRowSelection(manual, true)
      ElMessageBox({
        title: '提示',
        message: '确定删除当前说明书？删除后不可恢复',
        showCancelButton: true,
        type: 'error',
        beforeClose: async (action: Action, instance: MessageBoxState, done: () => void) => {
          if (action === 'cancel' || action === 'close') {
            done()
            return
          }

          if (action === 'confirm') {
            instance.cancelButtonLoading = true
            instance.confirmButtonLoading = true
            const res = await del(manualSelectIds.value)
            instance.cancelButtonLoading = false
            instance.confirmButtonLoading = false
            done()
            _getList()
            if (res.code === 20000) {
              HMessage.success('删除成功')
              return
            }
            HMessageBox.error(res.message)
          }
        },
      })
    }
  }

  /**
   * 获取批量操作的提醒
   * @param {('enable'|'disable'|'del')} type - 操作类型
   */
  const getMultipleOperateElMessageBoxMessage = (type: 'enable' | 'disable' | 'del') => {
    if (type === 'enable') {
      return '确定要启用选择的说明书？'
    }

    if (type === 'disable') {
      return '确定要禁用选择的说明书？'
    }

    if (type === 'del') {
      return '确定要删除选择的说明书？'
    }
  }

  /**
   * 批量操作调用
   * @param {('enable'|'disable'|'del')} type - 操作类型
   */
  const multipleOperateFnCall = async (type: 'enable' | 'disable' | 'del') => {
    if (type === 'enable') {
      return await enable(manualSelectIds.value)
    }

    if (type === 'disable') {
      return await disable(manualSelectIds.value)
    }

    if (type === 'del') {
      return await del(manualSelectIds.value)
    }
  }

  /**
   * 批量操作
   * @param {('enable'|'disable'|'del')} type - 操作类型
   */
  const handleMultipleOperate = (type: 'enable' | 'disable' | 'del') => {
    if (manualSelectIds.value.length <= 0) {
      HMessageBox.error('请选择说明书')
      return
    }

    ElMessageBox({
      title: '提示',
      message: getMultipleOperateElMessageBoxMessage(type),
      type: type === 'del' ? 'error' : 'warning',
      showCancelButton: true,
      async beforeClose(action, instance, done) {
        if (['close', 'cancel'].includes(action)) {
          done()
          return
        }

        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.cancelButtonLoading = true
          const res = await multipleOperateFnCall(type)
          instance.confirmButtonLoading = false
          instance.cancelButtonLoading = false
          done()
          _getList()
          if (res.code === 20000) {
            HMessage.success('操作成功')
            return
          }
          HMessageBox.error(res.message)
        }
      },
    })
  }

  defineExpose({ getList: _getList })
</script>

<template>
  <div v-loading="getListLoading" class="manual" element-loading-text="加载中...">
    <div class="header">
      <div class="btn_group">
        <HPlainButton v-permission="'know_manulAdd'" @click="manualCreateModalVisible = true"> 添加说明书 </HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="manualSelectIds.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <div v-permission="'know_manulEnabled'">
                <el-dropdown-item @click="handleMultipleOperate('enable')">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              </div>
              <div v-permission="'know_manulDisabled'">
                <el-dropdown-item @click="handleMultipleOperate('disable')">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              </div>
              <div v-permission="'know_manulDelete'">
                <el-dropdown-item @click="handleMultipleOperate('del')">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
              </div>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search">
        <el-input
          v-model.trim="getListParam.name"
          clearable
          placeholder="请输入关键字"
          @keyup.enter="_getList"
          @clear="_getList"
        />
        <HButton type="primary" @click="_getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>

    <div class="table">
      <el-table
        ref="tableInstance"
        :border="true"
        stripe
        resizable
        :data="manualList"
        height="100%"
        :tooltip-options="{
          popperClass: 'table-tooltip',
        }"
        @selection-change="handleManualSelect"
      >
        <!-- 选择 -->
        <el-table-column
          show-overflow-tooltip
          type="selection"
          width="40"
          fixed="left"
          :align="'center'"
        />

        <!-- 序号 -->
        <el-table-column
          show-overflow-tooltip
          type="index"
          label="序号"
          width="50"
          fixed="left"
          :align="'center'"
        />

        <!-- 说明书名称 -->
        <el-table-column show-overflow-tooltip prop="name" label="说明书名称" width="100" />

        <!-- 说明书内容 -->
        <!-- <el-table-column show-overflow-tooltip prop="content" label="说明书内容" min-width="300" /> -->

        <!-- 关联设备 -->
        <el-table-column show-overflow-tooltip prop="content" label="关联设备" width="240">
          <template #default="{ row }">
            {{ row.goods.join('、') }}
          </template>
        </el-table-column>

        <!-- 可见类型 -->
        <el-table-column show-overflow-tooltip prop="visibilityType" label="可见类型" width="80">
          <template #default="{ row }">
            {{
              row.visibilityType === 1
                ? '全部可见'
                : row.visibilityType === 2
                ? '部门可见'
                : '公司可见'
            }}
          </template>
        </el-table-column>

        <!-- 点击数 -->
        <el-table-column
          show-overflow-tooltip
          prop="clickNum"
          label="点击数"
          width="80"
        ></el-table-column>

        <!-- 创建时间 -->
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="140" />

        <!-- 更新时间 -->
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="140" />

        <!-- 状态 -->
        <el-table-column
          show-overflow-tooltip
          prop="status"
          label="状态"
          width="70"
          fixed="right"
          :align="'center'"
        >
          <template #default="scope">
            <div class="flex_justify_center">
              <HStatus v-if="scope.row.status === false">启用</HStatus>
              <HStatus v-if="scope.row.status === true" type="info">禁用</HStatus>
            </div>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column show-overflow-tooltip fixed="right" label="操作" width="135">
          <template #default="scope">
            <el-space :size="0" :spacer="spacer">
              <HLink v-permission="'know_manulPreview'" @click="handleManualPreview(scope.row.id)">预览</HLink>
              <HLink v-permission="'know_manulUpdate'" @click="handleManualUpdate(scope.row.id)">编辑</HLink>
              <h-link type="error" v-permission="'know_manulDelete'" @click="handleTableDelClick(scope.row)">删除</h-link>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination">
      <Pagination
        ref="paginationInstance"
        :list_total="listTotal"
        @size-change="_getList"
        @current-change="_getList"
      />
    </div>

    <manual-preview-modal
      v-model:visible="manualPreviewModalVisible"
      :manual-id="manualPreviewingId"
    ></manual-preview-modal>

    <manual-form-modal
      v-model:visible="manualCreateModalVisible"
      :manual-id="manualUpdatingId"
      @update="_getList"
    ></manual-form-modal>
  </div>
</template>

<style scoped lang="scss">
  :deep(.table-tooltip) {
    max-width: 300px !important;
    max-height: 150px !important;
    overflow: auto !important;
  }

  .manual {
    height: 100%;
    box-sizing: border-box;
    padding-top: 12px;
    display: flex;
    flex-direction: column;
    row-gap: 5px;

    .header {
      display: flex;
      justify-content: space-between;

      .btn_group {
        display: flex;
        column-gap: 5px;
      }

      .search {
        display: flex;
        column-gap: 5px;

        :deep(.el-input) {
          width: 120px;
        }
      }
    }

    .table {
      max-height: calc(100% - 66px);
    }

    .pagination {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
